package com.springboot.springboot_demo.controller;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

import com.google.common.collect.Lists;

/**
 * Title: ParallelStreamController.class <br>
 * Description: 线程安全验证及效率比较 <br>
 * Create DateTime:2022/5/24 13:23 <br>
 *
 * @author peichang.yang
 */
public class ParallelStreamController {

    // 线程安全
    private volatile int value;

    public static void main(String[] args) {

        // 线程不安全
        List<String> arrayList = Lists.newArrayList();

        // 线程安全
        List<String> copyOnWriteArray = new CopyOnWriteArrayList<>();

        // 准备数据1
        List<String> list1 = new CopyOnWriteArrayList<>();
        for (long i = 0; i < 300; i++) {
            list1.add(i + "");
        }

        // 准备数据2
        List<String> list2 = new CopyOnWriteArrayList<>();
        for (long i = 0; i < 1000; i++) {
            list2.add(i + "");
        }

        long startTime = System.currentTimeMillis();
        AtomicInteger index = new AtomicInteger();
        list1.parallelStream().forEach(v -> {
            list2.parallelStream().forEach(x -> {
                index.getAndAdd(1);
                // 线程不安全，丢数据
                arrayList.add(x);
                // 线程安全，不丢数据
                copyOnWriteArray.add(x);
            });
        });
        long endTime = System.currentTimeMillis();

        System.out.printf("效率 " + (endTime - startTime) + "\n");
        System.out.printf("index ------->" + index.get() + "\n");
        System.out.printf("arrayList ------->" + arrayList.size() + "\n");
        System.out.printf("copyOnWriteArray ------->" + copyOnWriteArray.size() + "\n");
    }

}
